﻿#include "opdb.h"

OpDb::OpDb(QObject *parent) : QObject(parent)
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");
}

OpDb::~OpDb()
{
    m_db.close();
}

OpDb &OpDb::getInstance()
{
    static OpDb opdb;
    return opdb;
}

void OpDb::connectDB()
{
    m_db.setHostName("127.0.0.1");
    m_db.setUserName("root");
    m_db.setPassword("12345678");
    m_db.setDatabaseName("chat");
    bool is = m_db.open();//连接
    if(is)
       qDebug()<<"connected DB success";
    else
        qDebug()<<"连接失败";
}

QList<QString> OpDb::getUserInfo(QString uname)
{
    QString sql = "select * from userinfo2 where id='"+uname+"'";
    QSqlQuery query;
    query.exec(sql);
    QList<QString> list;
    if(query.next())
    {
        for(int i=0;i<13;++i)
        {
            list.push_back(query.value(i).toString());
        }
    }
    else
    {
        QList<QString> list;
        for(int i=0;i<13;++i)
            list.append("");
        return list;
    }

    return list;
}

bool OpDb::saveUserInfo(QList<QString> info)
{
    QString sql = "select * from userinfo2 where id='"+info[0]+"'";
    QSqlQuery query;
    query.exec(sql);
    if(query.next())//有记录  则修改
    {
        sql = "update userinfo2 set nickname='"+info[2]+"', age='"+info[1]+"', sex='"+info[3]+"', phone='"+info[4]+"', address='"+info[5]+"', birthday='"+info[6]+"',  persig = '"+info[7]+"', rubric='"+info[8]+"',star='"+info[10]+"',zodiac='"+info[9]+"' where id = '"+info[0]+"'";
        qDebug()<<sql<<endl;
    }else//否则插入
    {
        QString head = QString(":/res/%1-head.jpg").arg(info[0]);
        sql = "insert into userinfo2 values('"+info[0]+"','"+info[2]+"','"+info[3]+"','"+info[1]+"','"+head+"','"+info[7]+"',0,'"+info[6]+"','"+info[10]+"','"+info[5]+"','"+info[4]+"','"+info[8]+"','"+info[9]+"')";
        qDebug()<<sql<<endl;
    }
    return query.exec(sql);
}

QString OpDb::getNickName(QString uname)
{
    QString sql = "select nickname from userinfo2 where id='"+uname+"'";
    QSqlQuery query;
    query.exec(sql);
    query.next();
    return query.value(0).toString();
}

QString OpDb::getHeadPath(QString id)
{
    QString sql = "select headurl from userinfo2 where id='"+id+"'";
    QSqlQuery query;
    query.exec(sql);
    query.next();
    return query.value(0).toString();
}

QString OpDb::getID(QString nickname)
{
    QString sql = "select id from userinfo2 where nickname='"+nickname+"'";
    QSqlQuery query;
    query.exec(sql);
    query.next();
    return query.value(0).toString();
}

QString OpDb::getGroupNotify(QString gid)
{
    QString sql = "select groupnotice from group1 where groupid='"+gid+"'";
    QSqlQuery query;
    query.exec(sql);
    query.next();
    return query.value(0).toString();
}

void OpDb::updateHead(QString id,QString path)
{
    QString sql = "update userinfo2 set headurl= '"+path+"' where id='"+id+"'";
    QString str = "/";
    QString str2 = "\\";
    sql = sql.replace(str2,str);
    QSqlQuery query;
    query.exec(sql);
}

